package day24;

import java.io.*;
import java.util.Date;

public class Student implements Serializable {
    //注1：序列化还可以添加UID，用于表示序列化的唯一标识
    //是为了保证序列化和反序列化是同一个对象
    private static final long serialVersionUID=12345678;
    //注2：序列化可以设置指定字段，忽略序列化
    //通过static修饰属性可以，因为它不属于类不属于对象
    //通过transient修饰的属性也可以，表示忽略序列化

    //注3：序列化和反序列化生成的文件，不要随便修改
    //否则文件损坏，会出现序列化异常
    StudentInfo info;
    Integer id;
    static String name;
    transient double score;
    Date birthday;

    public Student(Integer id, String name, double score, Date birthday) {
        this.id = id;
        this.name = name;
        this.score = score;
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", score=" + score +
                ", birthday=" + birthday +
                '}';
    }
}
class StudentInfo implements Serializable{
    Integer id;
    String sex;
    String phone;

    public StudentInfo(Integer id, String sex, String phone) {
        this.id = id;
        this.sex = sex;
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "StudentInfo{" +
                "id=" + id +
                ", sex='" + sex + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}
class Demo8{
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //1，序列化，生成对象到本地文件
        //output();
        //2.反序列化 通过本地文件，生成java中的对象
        input();
    }

    public static void input() throws IOException, ClassNotFoundException { //反序列化
        FileInputStream fis=new FileInputStream("C:\\Users\\梅穿内裤\\Desktop\\IOTest\\aa\\student.abc");
        ObjectInputStream ois=new ObjectInputStream(fis);
        Student s=(Student) ois.readObject();
        System.out.println(s);
        System.out.println(s.info);
        ois.close();
        fis.close();
    }
     public static void output() throws IOException { //序列化
         Student s=new Student(10, "张三", 99, new Date());
         StudentInfo info=new StudentInfo(10,"男","123456");
         s.info=info;
         FileOutputStream fos=new FileOutputStream("C:\\Users\\梅穿内裤\\Desktop\\IOTest\\aa\\student.abc");
         ObjectOutputStream oos=new ObjectOutputStream(fos);
         oos.writeObject(s);

         fos.close();
         oos.close();
     }
}